import { Directive, Injector, Input, ViewChild } from '@angular/core';
import { ApiResToComponent } from '@basic';
import { SFComponent, SFSchema } from '@delon/form';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { Observable } from 'rxjs';

import { BaseOfSimpleComponent } from './abstract-simple-component.base';

export interface FormItemCheckRule {
    // 需要验证的key
    itemKey: string;
    // 验证的方法
    checkFn: (v: any) => boolean;
}

/**
 * 基础表单控件
 */
@Directive()
export abstract class BaseOfSimpleForm<P, R> extends BaseOfSimpleComponent {
    @Input()
    item: any;

    @Input()
    type: 'add' | 'edit' | string = 'add'; // Modal打开的类型
    // 动态表单数据源组件
    @ViewChild('sf', { static: false }) sf!: SFComponent;

    abstract schema: SFSchema;

    modalRef: NzModalRef;

    protected constructor(protected override injector: Injector) {
        super(injector);
        this.modalRef = this.injector.get(NzModalRef);
    }

    // 数据提交
    submit(value: any): void {
        const Params = this.makeParams(value);
        if (Params !== undefined) {
            this.sendParams(Params);
        }
    }

    // 处理参数
    protected abstract makeParams(value: any): P;

    // API请求方法
    abstract sendToServer(value: any): Observable<ApiResToComponent<R>>;

    // 数据提交
    sendParams<T>(params: any): void {
        this.loading = true;
        this.sendToServer(params).subscribe((response: ApiResToComponent<R>) => {
            this.loading = false;
            if (response.isComplete) {
                this.afterSuccessPost(response);
            }
        });
    }

    /**
     * 获取纯净的form值
     * @param value
     */
    getValuesFormSf(value: any) {
        let _tempObj: any = {};
        Object.keys(this.schema?.properties ?? {}).forEach(key => {
            _tempObj[key] = value[key];
        });
        return _tempObj;
    }

    // 添加成功后操作
    afterSuccessPost(flag: any): void {
        // 将成员关键信息传递到主控制台
        this.modalRef.destroy(flag);
    }
}
